<template>
  <el-container style="padding: 20px; height: 100vh; display: flex;flex-direction: row; align-items: flex-start; ">
    <!-- 左侧参数设置 -->
    <el-aside width="45%" style="padding-right: 20px;">
      <el-card class="box-card" shadow="hover">
        <div slot="header" class="clearfix">
          <span>预测模型参数设置</span>
        </div>

        <el-form :model="form" label-width="100px" ref="formRef" label-position="right">
          <!-- 第一行：TimeStep, PredStep, Epochs -->
          <el-row :gutter="20">
            <el-col :span="8">
    <el-form-item label="TimeStep">
      <el-input
        v-model.number="form.TimeStep"
        type="text"
        class="full-width-input no-spin-button"
        placeholder="例如: 50"
        @input="limitTimeStep"
        @mousewheel.native.prevent
        @keydown.up.native.prevent
        @keydown.down.native.prevent
      />
    </el-form-item>
  </el-col>
  <el-col :span="8">
    <el-form-item label="PredStep">
      <el-input
        v-model.number="form.PredStep"
        type="text"
        class="full-width-input no-spin-button"
        placeholder="例如: 1"
        @input="limitPredStep"
        @mousewheel.native.prevent
        @keydown.up.native.prevent
        @keydown.down.native.prevent
      />
    </el-form-item>
  </el-col>
  <el-col :span="8">
    <el-form-item label="Epochs">
      <el-input
        v-model.number="form.Epochs"
        type="text"
        class="full-width-input no-spin-button"
        placeholder="例如: 100"
        @input="limitEpochs"
        @mousewheel.native.prevent
        @keydown.up.native.prevent
        @keydown.down.native.prevent
      />
    </el-form-item>
  </el-col>
          </el-row>

          <!-- 第二行：BatchSize, Learning Rate -->
          <el-row :gutter="20">
            <el-col :span="8">
    <el-form-item label="Batch Size">
      <el-input
        v-model.number="form.BatchSize"
        type="text"
        class="full-width-input no-spin-button"
        placeholder="16-512"
        @input="limitBatchSize"
        @mousewheel.native.prevent
        @keydown.up.native.prevent
        @keydown.down.native.prevent
      />
    </el-form-item>
  </el-col>

  <!-- Learning Rate -->
  <el-col :span="8">
    <el-form-item label="Learning Rate">
      <el-input
        v-model="form.LearningRate"
        type="text"
        class="full-width-input no-spin-button"
        placeholder="如: 0.001"
        @input="limitLearningRate"
        @mousewheel.native.prevent
        @keydown.up.native.prevent
        @keydown.down.native.prevent
      />
    </el-form-item>
  </el-col>
          </el-row>

          <!-- 第三行：StartFreq, FreqNum -->
          <el-row :gutter="20">
            <el-col :span="8">
    <el-form-item label="Start">
      <el-input
        v-model.number="form.StartFreq"
        type="text"
        class="full-width-input no-spin-button"
        placeholder="0-100"
        @input="limitStartFreq"
        @mousewheel.native.prevent
        @keydown.up.native.prevent
        @keydown.down.native.prevent
      />
    </el-form-item>
  </el-col>

  <!-- Freq Num -->
  <el-col :span="8">
    <el-form-item label="Freq Num">
      <el-input
        v-model.number="form.FreqNum"
        type="text"
        class="full-width-input no-spin-button"
        placeholder="1-30"
        @input="limitFreqNum"
        @mousewheel.native.prevent
        @keydown.up.native.prevent
        @keydown.down.native.prevent
      />
    </el-form-item>
  </el-col>
          </el-row>

          <!-- 文件上传 -->
          <el-row :gutter="20">
            <el-col :span="16">
              <el-form-item label="Data File">
                <el-upload
                class="upload-demo"
                  :show-file-list="false"
                  :http-request="customUpload"
                  :on-success="handleUploadSuccess"
                  :on-error="handleUploadError"
                  :before-upload="beforeUpload"
                  accept=".csv"
                >
                  <el-button slot="trigger" type="primary">选取CSV文件</el-button>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 提交按钮 -->
          <el-row :gutter="20">
            <el-col :span="8">
              <el-button @click="submitPrediction" type="success" style="width: 100%">开始预测</el-button>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
    </el-aside>

    <!-- 右侧结果展示 -->
    <el-main style="padding-left: 20px; transform: translateY(-19px) ">
      <!-- 在右侧结果展示部分顶部添加加载提示 -->
<div v-if="isLoading" style="text-align: center; padding: 20px;"class="loading-spinner">
    <div class="spinner"></div>

</div>
      <div v-if="result && !isLoading" style="margin-top: 0;">
        <el-card class="box-card" shadow="hover">
          <div slot="header">
            <span>预测结果</span>
            
          </div>

          <el-row :gutter="20" style="margin-bottom: 20px;">
            <el-col :span="12">
              <el-card shadow="hover">
                <div class="metric-box">
                  <p class="metric-label">平均 NRMSE</p>
                  <p class="metric-value">{{ result.avg_nrmse }}</p>
                </div>
              </el-card>
            </el-col>
            <el-col :span="12">
              <el-card shadow="hover">
                <div class="metric-box">
                  <p class="metric-label">预测耗时</p>
                  <p class="metric-value">{{ result.predict_time_ms }} ms</p>
                </div>
              </el-card>
            </el-col>
          </el-row>
          <div>
    <!-- 确保这里使用的是正确的属性名 -->
    <img :src="getImageSrc" alt="预测结果图" style="width: 100%; border-radius: 4px;" v-if="result && result.image_base64"/>
  </div>
          <!-- 图片展示 -->
          <h4 style="margin-bottom: 10px;">预测图表</h4>
         
          <div class="image-container">
  <div v-for="(img, index) in images" :key="index" class="image-item">
    <img :src="'data:image/png;base64,' + img.image_base64" :alt="img.filename" class="responsive-image"/>
  </div>
</div> 

          <!-- 下载按钮 -->
          <div style="margin-top: 20px;">
            <a 
    :href="'data:image/png;base64,' + images[0].image_base64" 
    :download="images[0].filename || 'prediction_result.png'" 
    style="text-decoration: none;"
  > <el-button type="info" icon="el-icon-download">下载预测图</el-button></a>
          </div>
        </el-card>
      </div>

      <!-- 默认提示信息 -->
      <div v-else style="text-align: center; color: #999; margin-top: 100px;">
        <p>请先设置参数并上传文件进行预测</p>
      </div>
    </el-main>
  </el-container>
</template>
  
  <script>
  import axios from 'axios';
  export default {
    data() {
      return {
        form: {
          TimeStep: 50,
          PredStep: 1,
          Epochs: 100,
          LearningRate: 0.001,
          StartFreq: 18,
          FreqNum: 15,
          BatchSize: 64,
          filename: null,
          username: sessionStorage.getItem('username') || ''
        },
        result: null,
        images:[],
        username: sessionStorage.getItem('username') || '',
        isLoading: false // 新增：用于标记是否正在加载预测结果
      };
    },
    methods: {
      // 文件上传相关方法
      handleUploadSuccess(response) {
      this.$message.success('文件上传成功');
      this.form.filename = response.data.filepath;
      this.uploadPercentage=1;
    },
    handleUploadError(error, file) {
      this.$message.error(`文件上传失败: ${file.name}`);
      this.uploadPercentage = 0; // 重置进度条
    },
    beforeUpload(file) {
      const isValidSize = file.size / 1024 / 1024 < 50; // 限制50MB
      if (!isValidSize) {
        this.$message.error('上传文件大小不能超过50MB!');
        return false;
      }

      const isValidType = /\.(csv)$/i.test(file.name); // 验证文件扩展名为 .csv
      if (!isValidType) {
        this.$message.error('只允许上传 CSV 文件 (.csv)');
        return false;
      }

      return true;
    },
    handleExceed(files, fileList) {
      this.$message.warning(`最多只能上传5个文件`);
    },
    handleProgress(event, file) {
      // 更新进度条
      this.uploadPercentage = Math.round((event.loaded / event.total) * 100);
    },
    getImageSrc() {
      if(this.result && this.result.image_base64) {
        return 'data:image/png;base64,' + this.result.image_base64;
      }
      return '';
    },
    customUpload(option) {
      const formData = new FormData();
      formData.append('file', option.file);
      formData.append('username', this.username);

      axios.post('http://127.0.0.1:5000/api/upload/spectrum', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then(response => {
        this.handleUploadSuccess(response);
      }).catch(error => {
        this.handleUploadError(error);
      });
    },
    async submitPrediction() {
  if (!this.form.filename) {
    this.$message.error('请先上传文件');
    return;
  }
  this.isLoading = true; // 开始预测前，设置为加载中状态
  try {
    const res = await axios.post(
      'http://127.0.0.1:5000/api/predict',
      this.form,
      {
        headers: {
          'Content-Type': 'application/json'
        }
      }
    );
    this.result=res.data.result
    this.images = res.data.images
    console.log(this.images[0].image_base64)
    

  } catch (error) {
    console.error('请求失败:', error.response?.data || error);
    this.$message.error(`请求失败，请查看控制台日志`);
  }finally{
    this.isLoading = false; // 不管成功还是失败，结束后都要关闭加载状态
  }
}
    }
  };
  </script>
  
  <style scoped>
  .full-width-input ::v-deep(.el-input__inner) {
  text-align: center;
  padding-left: 10px !important;
  padding-right: 10px !important;
  box-sizing: border-box;
  font-size: 14px;
  width: 100% !important;
}

/* 彻底隐藏数字输入框的上下箭头 */
.no-spin-button ::v-deep(input[type="text"])::-webkit-outer-spin-button,
.no-spin-button ::v-deep(input[type="text"])::-webkit-inner-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

  .loading-spinner {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}

.spinner {
  border: 8px solid #f3f3f3;
  border-top: 8px solid #3498db;
  border-radius: 50%;
  width: 50px;
  height: 50px;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
  .el-container {
  display: flex;
  flex-direction: row;
  align-items: flex-start; /* 内容顶部对齐 */
}
.result-container {
    display: flex;
    justify-content: space-between; /* 使两个结果项在容器内水平分布 */
    align-items: center; /* 垂直居中对齐 */
}

.result-item {
    text-align: center; /* 文本居中 */
    font-size: 14px; /* 减小字体大小 */
    margin: 0 20px; /* 调整左右间距 */
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}

.box-card {
  margin-bottom: 20px;
}

.el-card__header {
  background-color: #f9fafc;
  font-weight: bold;
}
.image-container {
  width: 100%;
  overflow: auto; /* 如果图片仍然超出容器，则允许滚动 */
}
.image-container img {
  max-width: 100%; /* 确保图片宽度不超过容器宽度 */
  height: auto; /* 自动调整高度以保持宽高比 */
  display: block;
  margin: 0 auto; /* 居中显示 */
}
.el-aside, .el-main {
  display: flex;
  flex-direction: column;
  /* 防止卡片内部内容撑高 */
  min-height: 0;
  min-width: 0;

}
</style>